<template>
  <view class="material-inventory">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-blue" :isBack="true">
      <view slot="content" class="nav-title">物料库存</view>
      <view slot="right" class="nav-right" @click="openFilterModal">
        <text class="cuIcon-filter text-white"></text>
        <text class="filter-text">筛选</text>
      </view>
    </cu-custom>

    <!-- 物料类型标签页 -->
    <view class="tabs-container">
      <scroll-view class="tabs-scroll" scroll-x="true" show-scrollbar="false">
        <view class="tabs-wrapper">
          <view
            v-for="tab in materialTypeTabs"
            :key="tab.value"
            class="tab-item"
            :class="{ active: activeTab === tab.value }"
            @click="switchTab(tab.value)"
          >
            <text class="tab-text">{{ tab.label }}</text>
            <view class="tab-indicator" v-if="activeTab === tab.value"></view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 库存列表 -->
    <view class="inventory-list">
      <view
        v-for="item in inventoryList"
        :key="item.id"
        class="inventory-item"
        :class="{ expanded: expandedItems.includes(item.id) }"
      >
        <!-- 默认显示区域 -->
        <view class="item-header" @click="toggleExpand(item.id)">
          <view class="header-content">
            <view class="primary-info">
              <view class="warehouse-info">
                <text class="warehouse-name">{{
                  item.warehouseName || "未知仓库"
                }}</text>
                <text class="location-code">{{
                  item.locationCode || "无库位"
                }}</text>
              </view>
              <view class="material-info">
                <view class="material-code">{{ item.materialCode }}</view>
                <view class="material-name">{{
                  item.materialName || "-"
                }}</view>
              </view>
              <view class="quantity-info">
                <text class="quantity-label">库存</text>
                <text class="quantity-value">{{
                  formatQuantity(item.quantity)
                }}</text>
                <text class="quantity-unit">{{
                  item.unitName || item.unit || ""
                }}</text>
              </view>
            </view>
            <view
              class="expand-icon"
              :class="{ rotated: expandedItems.includes(item.id) }"
            >
              <text class="iconfont icon-arrow-down"></text>
            </view>
          </view>
          <view class="status-indicator" :class="item.statusClass"></view>
          <view
            class="material-type-indicator"
            :class="item.materialTypeClass"
          ></view>
        </view>

        <!-- 展开显示区域 -->
        <view class="item-details" v-if="expandedItems.includes(item.id)">
          <view class="detail-grid">
            <view class="detail-item">
              <text class="label">物料名称</text>
              <text class="value">{{ item.materialName || "-" }}</text>
            </view>
            <view class="detail-item">
              <text class="label">物料类型</text>
              <text class="value">{{
                getMaterialTypeText(item.materialType)
              }}</text>
            </view>
            <view class="detail-item">
              <text class="label">规格</text>
              <text class="value">{{ item.specification || "-" }}</text>
            </view>
            <view class="detail-item">
              <text class="label">颜色</text>
              <text class="value">{{ item.color || "-" }}</text>
            </view>
            <view class="detail-item">
              <text class="label">单位</text>
              <text class="value">{{ item.unitName || item.unit || "-" }}</text>
            </view>
            <view class="detail-item">
              <text class="label">库存数量</text>
              <text class="value quantity">{{
                formatQuantity(item.quantity)
              }}</text>
            </view>
            <view class="detail-item">
              <text class="label">可用数量</text>
              <text class="value available">{{
                formatQuantity(item.availableQuantity)
              }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore" @click="loadMore">
      <text class="load-text">{{ loading ? "加载中..." : "加载更多" }}</text>
    </view>

    <!-- 筛选弹窗 -->
    <view
      class="filter-modal"
      v-if="showFilterModal"
      @click="showFilterModal = false"
    >
      <view class="filter-content" @click.stop>
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
          <text class="close-btn" @click="showFilterModal = false">×</text>
        </view>
        <view class="filter-body">
          <!-- 模糊查询字段 -->
          <view class="filter-group">
            <text class="group-title">查询条件</text>
            <view class="input-group">
              <view class="input-item">
                <text class="input-label">仓库名称</text>
                <input
                  class="filter-input"
                  type="text"
                  placeholder="请输入仓库名称"
                  v-model="filterForm.warehouseName"
                />
              </view>
              <view class="input-item">
                <text class="input-label">库位编码</text>
                <input
                  class="filter-input"
                  type="text"
                  placeholder="请输入库位编码"
                  v-model="filterForm.locationCode"
                />
              </view>
              <view class="input-item">
                <text class="input-label">物料编码</text>
                <input
                  class="filter-input"
                  type="text"
                  placeholder="请输入物料编码"
                  v-model="filterForm.materialCode"
                />
              </view>
              <view class="input-item">
                <text class="input-label">物料名称</text>
                <input
                  class="filter-input"
                  type="text"
                  placeholder="请输入物料名称"
                  v-model="filterForm.materialName"
                />
              </view>
              <view class="input-item">
                <text class="input-label">规格</text>
                <input
                  class="filter-input"
                  type="text"
                  placeholder="请输入规格"
                  v-model="filterForm.specification"
                />
              </view>
              <view class="input-item">
                <text class="input-label">颜色</text>
                <input
                  class="filter-input"
                  type="text"
                  placeholder="请输入颜色"
                  v-model="filterForm.color"
                />
              </view>
            </view>
          </view>

          <view class="filter-group">
            <text class="group-title">物料类型</text>
            <view class="checkbox-group">
              <view
                v-for="type in materialTypes"
                :key="type.value"
                class="checkbox-item"
                :class="{ checked: selectedTypes.includes(type.value) }"
                @click="toggleType(type.value)"
              >
                <text class="checkbox-text">{{ type.label }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="filter-footer">
          <view class="filter-btn reset" @click="resetFilter">重置</view>
          <view class="filter-btn confirm" @click="applyFilter">确定</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "MaterialInventory",
  data() {
    return {
      searchKeyword: "",
      inventoryList: [],
      expandedItems: [],
      loading: false,
      hasMore: true,
      pageNo: 1,
      pageSize: 20,
      showFilterModal: false,
      selectedTypes: [],
      selectedStatuses: [],
      activeTab: "all",
      filterForm: {
        warehouseName: "",
        locationCode: "",
        materialCode: "",
        materialName: "",
        specification: "",
        color: "",
      },
      materialTypes: [
        { value: 1, label: "型材" },
        { value: 2, label: "配件" },
        { value: 3, label: "辅件" },
        { value: 4, label: "其他" },
        { value: 5, label: "余料" },
        { value: 6, label: "半料" },
      ],
      materialTypeTabs: [
        { value: "all", label: "全部" },
        { value: 1, label: "型材" },
        { value: 2, label: "配件" },
        { value: 3, label: "辅件" },
        { value: 4, label: "其他" },
        { value: 5, label: "余料" },
        { value: 6, label: "半料" },
      ],
      stockStatuses: [
        { value: "normal", label: "正常" },
        { value: "low", label: "库存不足" },
        { value: "out", label: "缺货" },
        { value: "locked", label: "锁定" },
      ],
    };
  },

  onLoad() {
    this.loadInventoryData();
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  methods: {
    async loadInventoryData(isRefresh = false) {
      if (this.loading) return;

      this.loading = true;

      if (isRefresh) {
        this.pageNo = 1;
        this.inventoryList = [];
        this.hasMore = true;
      }

      try {
        const materialTypes = this.getFilteredMaterialTypes();
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          searchKeyword: this.searchKeyword,
          materialTypes: materialTypes,
          warehouseName: this.filterForm.warehouseName,
          locationCode: this.filterForm.locationCode,
          materialCode: this.filterForm.materialCode,
          materialName: this.filterForm.materialName,
          specification: this.filterForm.specification,
          color: this.filterForm.color,
        };

        const response = await this.$http.get("/wms/inventory/queryForMobile", {
          params: params,
        });

        if (response.data.success) {
          const newData = response.data.result?.records || [];

          // 为每个库存项添加状态类和状态文本
          const processedData = newData.map((item) => {
            const processedItem = {
              ...item,
              statusClass: this.calculateStatusClass(item),
              statusText: this.calculateStatusText(item),
              materialTypeClass: this.calculateMaterialTypeClass(
                item.materialType
              ),
            };
            return processedItem;
          });

          if (isRefresh) {
            this.inventoryList = processedData;
          } else {
            this.inventoryList = [...this.inventoryList, ...processedData];
          }

          this.hasMore = newData.length === this.pageSize;
          this.pageNo++;
        } else {
          const errorMessage = response.data.message || "加载失败";
          console.error("API返回错误:", errorMessage);
          uni.showToast({
            title: errorMessage,
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载库存数据失败:", error);
        let errorMessage = "网络错误";

        if (error.errMsg) {
          errorMessage = error.errMsg;
        } else if (error.data && error.data.message) {
          errorMessage = error.data.message;
        } else if (error.message) {
          errorMessage = error.message;
        }

        uni.showToast({
          title: errorMessage,
          icon: "none",
        });
      } finally {
        this.loading = false;
        if (isRefresh) {
          uni.stopPullDownRefresh();
        }
      }
    },

    refreshData() {
      this.loadInventoryData(true);
    },

    loadMore() {
      if (!this.hasMore || this.loading) return;
      this.loadInventoryData();
    },

    onSearchInput() {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.refreshData();
      }, 500);
    },

    toggleExpand(itemId) {
      const index = this.expandedItems.indexOf(itemId);
      if (index > -1) {
        this.expandedItems.splice(index, 1);
      } else {
        this.expandedItems.push(itemId);
      }
    },

    toggleType(typeValue) {
      const index = this.selectedTypes.indexOf(typeValue);
      if (index > -1) {
        this.selectedTypes.splice(index, 1);
      } else {
        this.selectedTypes.push(typeValue);
      }
    },

    toggleStatus(statusValue) {
      const index = this.selectedStatuses.indexOf(statusValue);
      if (index > -1) {
        this.selectedStatuses.splice(index, 1);
      } else {
        this.selectedStatuses.push(statusValue);
      }
    },

    resetFilter() {
      this.selectedTypes = [];
      this.selectedStatuses = [];
      this.filterForm = {
        warehouseName: "",
        locationCode: "",
        materialCode: "",
        materialName: "",
        specification: "",
        color: "",
      };
    },

    applyFilter() {
      this.showFilterModal = false;
      this.refreshData();
    },

    getMaterialTypeText(type) {
      const typeObj = this.materialTypes.find((t) => t.value === type);
      return typeObj ? typeObj.label : "未知";
    },

    calculateStatusClass(item) {
      if (!item.availableQuantity || item.availableQuantity <= 0) {
        return "status-out";
      } else if (item.availableQuantity < item.quantity * 0.2) {
        return "status-low";
      } else if (item.lockedQuantity > 0) {
        return "status-locked";
      }
      return "status-normal";
    },

    calculateStatusText(item) {
      if (!item.availableQuantity || item.availableQuantity <= 0) {
        return "缺货";
      } else if (item.availableQuantity < item.quantity * 0.2) {
        return "库存不足";
      } else if (item.lockedQuantity > 0) {
        return "部分锁定";
      }
      return "正常";
    },

    formatQuantity(quantity) {
      if (!quantity) return "0";
      return parseFloat(quantity).toFixed(2);
    },

    viewDetails(item) {
      uni.navigateTo({
        url: `/pages/wms/inventory/detail?id=${item.id}`,
      });
    },

    adjustInventory(item) {
      uni.navigateTo({
        url: `/pages/wms/inventory/adjust?id=${item.id}`,
      });
    },

    moveInventory(item) {
      uni.navigateTo({
        url: `/pages/wms/inventory/move?id=${item.id}`,
      });
    },

    switchTab(tabValue) {
      this.activeTab = tabValue;
      this.refreshData();
    },

    getFilteredMaterialTypes() {
      if (this.activeTab === "all") {
        // 全部标签页：如果有筛选条件就用筛选条件，否则返回空字符串（查询所有）
        return this.selectedTypes.length > 0
          ? this.selectedTypes.join(",")
          : "";
      } else {
        // 特定标签页：始终包含当前tab的物料类型
        const tabTypes = [this.activeTab];
        // 如果还有额外的筛选条件，则取交集
        if (this.selectedTypes.length > 0) {
          const intersection = tabTypes.filter((type) =>
            this.selectedTypes.includes(type)
          );
          // 如果交集为空，说明筛选条件与当前tab不匹配，返回当前tab类型
          return intersection.length > 0
            ? intersection.join(",")
            : tabTypes.join(",");
        }
        return tabTypes.join(",");
      }
    },

    calculateMaterialTypeClass(materialType) {
      const typeClassMap = {
        1: "type-profile", // 型材 - 蓝色
        2: "type-accessory", // 配件 - 绿色
        3: "type-auxiliary", // 辅件 - 橙色
        4: "type-other", // 其他 - 灰色
        5: "type-surplus", // 余料 - 紫色
        6: "type-semi", // 半料 - 红色
      };
      return typeClassMap[materialType] || "type-default";
    },

    openFilterModal() {
      this.showFilterModal = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.material-inventory {
  background: #f5f7fa;
  min-height: 100vh;
}

// 自定义导航栏样式
.nav-title {
  font-size: 36rpx;
  font-weight: 600;
  color: white;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 16rpx;

  .filter-text {
    font-size: 28rpx;
    color: white;
  }
}

// 标签页样式
.tabs-container {
  background: white;
  border-bottom: 1rpx solid #f0f0f0;
}

.tabs-scroll {
  white-space: nowrap;
}

.tabs-wrapper {
  display: flex;
  padding: 0 24rpx;
}

.tab-item {
  position: relative;
  padding: 24rpx 32rpx;
  margin-right: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s ease;

  .tab-text {
    font-size: 28rpx;
    color: #8c8c8c;
    transition: color 0.3s ease;
  }

  .tab-indicator {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 4rpx;
    background: #1890ff;
    border-radius: 2rpx;
  }

  &.active {
    .tab-text {
      color: #1890ff;
      font-weight: 600;
    }
  }
}

.inventory-list {
  padding: 24rpx;
}

.inventory-item {
  background: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;

  &.expanded {
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
  }
}

.item-header {
  padding: 32rpx 24rpx;
  position: relative;
  cursor: pointer;

  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .primary-info {
    flex: 1;

    .warehouse-info {
      display: flex;
      align-items: center;
      gap: 16rpx;
      margin-bottom: 12rpx;

      .warehouse-name {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
        font-size: 24rpx;
        font-weight: 500;
      }

      .location-code {
        background: #f0f2f5;
        color: #595959;
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
        font-size: 24rpx;
      }
    }

    .material-info {
      margin-bottom: 12rpx;

      .material-code {
        font-size: 32rpx;
        font-weight: 600;
        color: #262626;
        margin-bottom: 4rpx;
      }

      .material-name {
        font-size: 26rpx;
        color: #8c8c8c;
      }
    }

    .quantity-info {
      display: flex;
      align-items: baseline;
      gap: 8rpx;

      .quantity-label {
        font-size: 24rpx;
        color: #8c8c8c;
      }

      .quantity-value {
        font-size: 28rpx;
        font-weight: 600;
        color: #1890ff;
      }

      .quantity-unit {
        font-size: 24rpx;
        color: #8c8c8c;
      }
    }
  }

  .expand-icon {
    width: 48rpx;
    height: 48rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #8c8c8c;
    transition: transform 0.3s ease;

    &.rotated {
      transform: rotate(180deg);
    }
  }

  .status-indicator {
    position: absolute;
    top: 0;
    right: 0;
    width: 8rpx;
    height: 100%;

    &.status-normal {
      background: #52c41a;
    }

    &.status-low {
      background: #faad14;
    }

    &.status-out {
      background: #ff4d4f;
    }

    &.status-locked {
      background: #722ed1;
    }
  }

  .material-type-indicator {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 100%;
    height: 6rpx;

    &.type-profile {
      background: #1890ff; // 型材 - 蓝色
    }

    &.type-accessory {
      background: #52c41a; // 配件 - 绿色
    }

    &.type-auxiliary {
      background: #fa8c16; // 辅件 - 橙色
    }

    &.type-other {
      background: #8c8c8c; // 其他 - 灰色
    }

    &.type-surplus {
      background: #722ed1; // 余料 - 紫色
    }

    &.type-semi {
      background: #f5222d; // 半料 - 红色
    }

    &.type-default {
      background: #d9d9d9; // 默认 - 浅灰色
    }
  }
}

.item-details {
  border-top: 1rpx solid #f0f0f0;
  padding: 32rpx 24rpx;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24rpx 32rpx;
  margin-bottom: 32rpx;
}

.detail-item {
  .label {
    display: block;
    font-size: 24rpx;
    color: #8c8c8c;
    margin-bottom: 8rpx;
  }

  .value {
    display: block;
    font-size: 28rpx;
    color: #262626;
    font-weight: 500;

    &.quantity {
      color: #1890ff;
    }

    &.available {
      color: #52c41a;
    }

    &.status {
      &.status-normal {
        color: #52c41a;
      }

      &.status-low {
        color: #faad14;
      }

      &.status-out {
        color: #ff4d4f;
      }

      &.status-locked {
        color: #722ed1;
      }
    }
  }
}

.action-buttons {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  flex: 1;
  height: 72rpx;
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  font-size: 26rpx;
  font-weight: 500;
  transition: all 0.3s ease;

  &.primary {
    background: #1890ff;
    color: white;

    &:active {
      background: #096dd9;
    }
  }

  &.secondary {
    background: #f0f2f5;
    color: #595959;

    &:active {
      background: #d9d9d9;
    }
  }

  &.tertiary {
    background: #fff2e8;
    color: #fa8c16;

    &:active {
      background: #ffd8bf;
    }
  }
}

.load-more {
  padding: 32rpx;
  text-align: center;

  .load-text {
    color: #8c8c8c;
    font-size: 28rpx;
  }
}

.filter-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}

.filter-content {
  background: white;
  border-radius: 24rpx 24rpx 0 0;
  width: 100%;
  max-height: 80vh;
  overflow: hidden;
}

.filter-header {
  padding: 32rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .filter-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #262626;
  }

  .close-btn {
    font-size: 48rpx;
    color: #8c8c8c;
    line-height: 1;
  }
}

.filter-body {
  padding: 32rpx 24rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.filter-group {
  margin-bottom: 40rpx;

  .group-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #262626;
    margin-bottom: 20rpx;
  }
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.checkbox-item {
  padding: 16rpx 24rpx;
  background: #f8f9fa;
  border-radius: 32rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;

  &.checked {
    background: #e6f7ff;
    border-color: #1890ff;
    color: #1890ff;
  }

  .checkbox-text {
    font-size: 26rpx;
  }
}

.filter-footer {
  padding: 24rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  gap: 16rpx;
}

// 输入框组样式
.input-group {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.input-item {
  display: flex;
  flex-direction: column;
  gap: 12rpx;

  .input-label {
    font-size: 26rpx;
    color: #262626;
    font-weight: 500;
  }

  .filter-input {
    height: 72rpx;
    background: #f8f9fa;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    border: 2rpx solid transparent;
    transition: all 0.3s ease;

    &:focus {
      background: white;
      border-color: #1890ff;
    }
  }
}

.filter-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: 500;

  &.reset {
    background: #f0f2f5;
    color: #595959;
  }

  &.confirm {
    background: #1890ff;
    color: white;
  }
}
</style>
